<template>
    <div>
        <el-tabs type="card" @tab-click="handleTabClick">
                <el-tab-pane :label="item.name" v-for="(item, index) in formtable" :key="index" >
                    <div style="padding:10px 20px;">    
                       <div v-if="item.istable">
                          <label v-for="(itemw, i) in item.subitem" :key="i" style="display:inline-block;margin:0 10px;">
                            <el-button type="text" :icon="itemw.icon" @click="getWlClick(itemw.value, index + 1, item)">{{ itemw.name }}</el-button>
                          </label>
                       </div>
                    </div>
                    <div v-if="item.value=='image'">
                        <el-upload
                            :http-request="uploadServerLog"
                            :show-file-list="false"
                            action="##"
                            class="upload-demo mr10 mb15"
                            multiple >
                            <div style="vertical-align: middle;margin-top:8px;">
                            <label v-if="imageUrl && imageUrl.length > 0" style="display:inline-block;height:50px;margin:10px;vertical-align:top;">
                                <img v-for="(item, index) in imageUrl" :key="index" :src="item.url" class="img" style="width:50px;" />
                            </label>
                            <label style="display:inline-block;border:3px dashed #999;border-radius: 8px;width:50px;height:50px;margin:10px;padding-top:4px;">
                                <i class="el-icon-plus avatar-uploader-icon" style="font-size:36px;font-weight:600;color:#999;"></i>
                            </label>
                            </div>
                        </el-upload>  
                    </div>
                    <div v-else>
                      <div v-loading="tableLoading">
                        <drawerTables :selectDialogIndex="selectDialogIndex" :keyName="keyName" :tableData="item.tableData" :tableInfo="item.tableHeader" :zidianData="item.datadictList" @selectTabel="selectTabel"></drawerTables>
                      </div>
                    </div>
                </el-tab-pane>
        </el-tabs>
        <el-dialog :title="dialogtitle" :visible.sync="dialogVisible" width="60%" append-to-body>
            <selectDialog v-if="dialogVisible" :total="diatotal" :tableInfo="selectInfo" :tableData="selectData" :searchField="searchField" :searchForm="searchForm" @handlerSearch="handlerSearch" @handlerSubmit="handlerSubmit"></selectDialog>
        </el-dialog>
        
    </div>
</template>
<script>
import { crudModuleListApi, crudModuleSaveDataApi, crudModuleInfoApi, 
    crudModuleFindApi, configDictDataApi, crudFormInfoApi, crudModuleBatchDelApi, crudModuleDelApi, databaseInfoApi } from '@/api/develop'
import { getDictDatainfoApi, getDictDataListApi } from '@/api/form'
import { uploader } from '@/utils/uploadCloud'
import drawerTables from './table'
import selectDialog from './selectDialog.vue'
import { EventBus } from '@/libs/bus'
export default {
    name: 'HelloWorld',
    components: { drawerTables, selectDialog },
    data() {
        return {
            tableLoading: true,
            tabactive:'1',
            imageUrl: [],
            percentShow: false,
            dialogVisible: false,
            dialogImageUrl:'',
            tableInfo:[],
            gytableInfo:[],
            gytableData:[],
            getableData:[],
            getabelDataid:[],
            getableInfo:[],
            khtableData:[],
            khtableInfo:[],
            
            guigezidian: {
                types: "guige",
                level: 1,
                pid:'',
                name:'', 
            },
            tablebaseSearch:{
                is_field_all:'',
                is_system:1,
                limit: 100,
                order_by:{},
                page:1,
                scope_frame:'all',
                show_search_type:'0',
                view_search: [],
                view_search_boolean:'',
            },
            selectInfo: [],
            selectData: [],
            selectedData:[], // 选中数据
            dialogtitle:'',
            searchField:[ {
                field_name:'代码或名称',
                field_name_en:'name',
                form_value:'input',
                placeholder:'请输入代码或名称关键字'
            }],
            searchForm: {
                name:''
            },
            selectDialogIndex: 1,
            childform: {
                wuliaodanganid: '' 
            },
            khselected:[],
            geselected:[],
            gyselected:[],
            selectedlist:[],
            optionStatus:[],// 状态选择
            formtable: [],
            formlength: 0,
            wuliaoleibieData: [], // 物料类别规格数据
            selectName:'',
            dictForm: {
                types: '',
                level: 1,
                pid:''
            },
            selectFiledData: {

            },
            diatotal: 0,
            tabIndexs: 0
        }
    },
    props: {
        testFormData: {
            type: Object,
            default:()=>{
                return {}
            }
        },
        keyName: {
            type: String,
            default: ''
        },
        id: { // 档案id
           type: Number,
           default: 0
        },
        typeid: { // 档案类别id
            type: [Number, String],
            default: 0
        },
        isSubmit: {
            type: Number,
            default: 0
        },
        formDataAll: {
            type: Array,
            default: ()=>{
                return []
            }
        },
        pagestatus: { // 判断是否显示表单
            type: Number, 
            default: 1
        },
        flagStatu: {
            type: Number,
            default: 0,
        },
        treeData: {
            type: [Array, Object],
            default: ()=>{
                return []
            }
        }
       
    },
    watch: {
        isSubmit(newValue) {
            if(newValue==1){
                this.wuinit();
            }
        },
        
      
    },
    mounted(){
        this.wuinit();
      
    },
    methods:{
       
        async wuinit(){
            if(this.flagStatu != 2){
                this.tableLoading = true;
                this.formtable = this.formDataAll;
                await this.hadnlerInofinit();
                this.$emit("handlerisSubmit")
              
            }
        },
        handlerFilterD(){
            this.formlength = 0;
            this.formtable = this.formDataAll;
            this.formtable.map((item)=>{
                if(item.istable){
                    this.formlength++;
                }
            })
        },
        // tab切换
        async handleTabClick(event){
            let i = event.index;
            this.selectDialogIndex = Number(i) + 1;
            this.tableData = this.formtable[i].tableData;

           
        },
        // 获取表格数据及字典数据
        async hadnlerwlqdInofinit(){
            let i= 0;
            for(let i=0;i<this.formtable.length;i++){
                if(this.formtable[i].istable){
                    this.formtable[i].tableData = []
                    if(this.formtable[i].value){
                        let resdatas = await crudModuleInfoApi(this.formtable[i].value, 0);
                        await this.handlerallFiledData(resdatas, i)
                        if(this.id){ 
                            if(this.keyName=='wuliaoleibieshuxing'){ // 物料类别属性
                                this.formtable[i].search['wuliaoleibiebianmaid'] = this.id;
                            }else if(this.keyName == 'gongxushezhong'){ // 工序设置
                                this.formtable[i].search['fugongxu'] = this.id;
                            }
                            let search1 = this.formtable[i].search;
                            let search2 = this.tablebaseSearch;
                            let search3 = {...search1, ...search2}
                            let data = await crudModuleListApi(this.formtable[i].value, search3);
                            await this.handlerTableAllData(data, i);
                            
                        }
                    }
                }
            }
           
        },
        // 获取表格数据及字典数据
        async hadnlerInofinit(){
            let i= 0;
            for(let i=0;i<this.formtable.length;i++){
                if(this.formtable[i].istable){
                    this.formtable[i].tableData = []
                    if(this.formtable[i].value){
                        let resdatas = await crudModuleInfoApi(this.formtable[i].value, 0);
                        await this.handlerallFiledData(resdatas, i)
                        if(this.id){ 
                            if(this.keyName=='wuliaoleibieshuxing'){ // 物料类别属性
                                this.formtable[i].search['wuliaoleibiebianmaid'] = this.id;
                            }else if(this.keyName=='wuliaoqingdanbiao'){ // 物料清单搜索
                                this.formtable[i].search['fuwuliaobianmaid'] = this.id;
                            }else if(this.keyName == 'gongxushezhong'){ // 工序设置
                                this.formtable[i].search['fugongxu'] = this.id;
                            }else{ // 物料档案
                                this.formtable[i].search['wuliaodanganid'] = this.id;
                            }
                            let search1 = this.formtable[i].search;
                            let search2 = this.tablebaseSearch;
                            let search3 = {...search1, ...search2}
                            let data = await crudModuleListApi(this.formtable[i].value, this.formtable[i].search);
                            await this.handlerTableAllData(data, i);
                            
                        }
                    }
                }
            }
           
        },

        // 获取表头数据
        async handlerallFiledData(resdata, index){
            let showFieldData = resdata.data.showField;
            let searchFieldData = resdata.data.seniorSearch;
            let searchdefault = this.formtable[index].search;
            let objs = {},searchobj = {},dataictnamearr=[]
            let fileallData = [];
            for(let i=0;i < showFieldData.length;i++){
                objs[showFieldData[i].field_name_en] = ''
                objs.disabled = false;
                if(searchFieldData.length > 0){
                    if(searchFieldData[i]){
                       searchobj[searchFieldData[i].field_name_en] = ''
                    }
                }
                if(showFieldData[i].field_name_en != 'fuwuliaobianmaid'){
                    fileallData.push(showFieldData[i]); // 在索引1的位置
                }
            }
           
            this.formtable[index].form = objs;
            this.formtable[index].search = {...searchdefault, ...searchobj};
            this.formtable[index].tableHeader = fileallData;
            if(index == 0 ){
               this.tableLoading = false;
            }
            await this.handlerDict(this.formtable[index].tableHeader, index)
            
            
        },
         // 表格展示数据
        async handlerTableAllData(data, index){
            if(data.status==200){
                let resdataList = data.data.list;
                for(let i=0;i < resdataList.length;i++){
                    if(resdataList[i].zhuangtai && resdataList[i].zhuangtai.length > 0){ // 状态
                        resdataList[i].zhuangtai = (resdataList[i].zhuangtai).join(',')
                    }
                    if(resdataList[i].laiyuan && resdataList[i].laiyuan.length > 0){ // 状态
                        resdataList[i].laiyuan = (resdataList[i].laiyuan).join(',')
                    }
                    if(resdataList[i].bibie && resdataList[i].bibie.length > 0){ // 币别
                        resdataList[i].bibie = (resdataList[i].bibie).join(',')
                    }
                    if(resdataList[i].wuliaodanganid){
                        let wlbmobj = { id: this.id, name: resdataList[i].wuliaodanganid || '' }
                        resdataList[i].wuliaodanganid = wlbmobj
                    }
                    if(resdataList[i].wuliaoleibiebianmaid){
                        let wlbmobj = { id: this.id, name: resdataList[i].wuliaoleibiebianmaid || '' }
                        resdataList[i].wuliaoleibiebianmaid = wlbmobj
                    }
                }
                this.formtable[index].tableData = resdataList;
                this.formtable[index].oldData = JSON.parse(JSON.stringify(resdataList));
                
            }

        },

        async handlerDict(headerData, index){
          let itemdata = headerData;
          let obj = {}
          if(itemdata && itemdata.length > 0){
          for(let i=0;i<itemdata.length;i++){
             if(itemdata[i].data_dict_id){ // 字典查询下拉选择框数据
                obj[itemdata[i].field_name_en] = []
                let dataictnamearr = []
                let datadict = await getDictDatainfoApi(itemdata[i].data_dict_id)
                dataictnamearr.push(datadict.data.ident);
                this.dictForm.types = dataictnamearr;
                let datadictDta = await getDictDataListApi(this.dictForm)
                obj[itemdata[i].field_name_en] = datadictDta.data.list;
                // this.formtable[index].datadictList = datadictDta.data.list
             }else if(itemdata[i].association_crud_id && itemdata[i].field_name_en !='wuliaobianmaid'){ // 关联表选择查询
                let database = await databaseInfoApi(itemdata[i].association_crud_id)
                let tabbasename = database.data.table_name_en;
                let datalist = await crudModuleListApi(tabbasename, {page: 1, limit: 100});
                obj[itemdata[i].field_name_en] = datalist.data.list;
                // this.formtable[index].datadictList = datadictDta.data.list
             }
          }
          this.formtable[index].datadictList = obj;
       
        }
      },
        
        
        // 选中表格数据返回
        selectTabel(val){
            if(val && val.length > 0){
               this.formtable[this.selectDialogIndex-1].selectData = val
                
            }
        },
        // 搜索 返回
        handlerSearch(data){
            if(this.selectName == 'guige'){
                this.guigezidian.name = data.name;
                this.getGuigezidian(this.guigezidian, this.selectDialogIndex);
            // }else if(this.selectName == this.keyName){
            //     let wldadatas = crudModuleListApi(this.keyName);
            }else{
                this.searchForm = {...this.tablebaseSearch, ...data};
                this.getStTableBase(this.selectName, searchForm, this.selectDialogIndex, this.selectFiledData);
            }
        },
        // 提交数据返回
        handlerSubmit(index=0, data){
            if(index==0){ // 取消关闭弹窗
                this.dialogVisible = false;
            }else{
                if(this.selectName == 'guige'){ // 物料档案规格表
                    if(data.length > 0){
                        for(let i=0;i<data.length;i++){
                            let formobj  = {}
                            formobj = JSON.parse(JSON.stringify(this.formtable[this.selectDialogIndex-1].form));
                            formobj.guigedaima = data[i].value;
                            formobj.guigeleixing = data[i].name;
                            formobj.zhuangtai = '正常'; //{name:'正常', color:'#303030'};
                            this.formtable[this.selectDialogIndex-1].tableData.push(formobj);
                        }
                    }  
                }else{
                    if(data.length > 0){
                        for(let i=0;i<data.length;i++){
                            const keys = Object.keys(this.formtable[this.selectDialogIndex-1].form)
                            if(this.keyName =='wuliaoqingdanbiao'){ // 物料清单表
                                let formobj = JSON.parse(JSON.stringify(this.formtable[this.selectDialogIndex-1].form));
                                formobj.wuliaobianmaid = data[i].id;
                                formobj.item_depc = data[i].item_depc;
                                formobj.item_sn = data[i].item_sn
                                formobj.unit = data[i].unit;
                                formobj.id = ''
                                this.formtable[this.selectDialogIndex-1].tableData.push(formobj);
                                EventBus.$emit('event-tree-grandchild', this.formtable[this.selectDialogIndex-1].tableData)
                            }else{
                                if(keys && keys.length > 0){
                                    let formobj = JSON.parse(JSON.stringify(this.formtable[this.selectDialogIndex-1].form));
                                    for(let key of keys){
                                        if(data[i][key]){
                                            if(key in data[i]){
                                                formobj[key] = data[i][key];
                                            }
                                        }
                                    }
                                    if(formobj.kehao){ // 档案客户信息表批量添加要获取客户信息的id才能把客号添加成功
                                        formobj.kehaoid = data[i].id;
                                    }
                                    if(formobj.zhuangtai && formobj.zhuangtai.length > 0){
                                        formobj.zhuangtai = formobj.zhuangtai.join(',')
                                    }else{
                                        if(formobj.zhuangtai=='' || formobj.zhuangtai.length == 0){
                                            formobj.zhuangtai = '正常'
                                        } 
                                        
                                    }
                                    if(formobj.laiyuan && formobj.laiyuan.length > 0){
                                        formobj.laiyuan = formobj.laiyuan.join(',')
                                    }
                                    if(formobj.gongxudaima){
                                    formobj.gongxudaimaid = data[i].id;
                                    }
                                    this.formtable[this.selectDialogIndex-1].tableData.push(formobj);
                                }else{
                                    this.formtable[this.selectDialogIndex-1].tableData.push(data[i]);
                                }
                            }
                        }
                    }  
                }
                if(index==2){ // 确认退出关闭弹窗
                    this.dialogVisible = false;
                }
            }
            
        },

        // 添加，选择，删除等方法
        async getWlClick(val, indexstatus=0, item){
            this.selectDialogIndex = indexstatus;
            this.dialogtitle = item.name;
            if(val=='add'){ // 添加
                this.selectName = item.subitem[0].tablename;
                if(this.selectName=='guige'){ // 选择规格(规格字典表)
                   this.searchForm  = { name: ''}
                   this.searchField = [ {field_name_en: 'name', field_name:'代码或名称'}]; 
                   this.getGuigezidian(this.guigezidian, indexstatus);
                }else{ // 实体表
                    if(this.selectName){ // 根据从其他表添加数据
                        let resdatas = await crudModuleInfoApi(this.selectName, item.subitem[0].id || 0);
                        if(resdatas.status==200){
                            this.selectFiledData = resdatas.data;
                            this.getStTableBase(this.selectName, this.formtable[indexstatus-1].search, indexstatus, resdatas.data);
                            
                        }
                    }else{ // 直接添加数据
                        let dataheader = this.formtable[indexstatus-1].tableHeader;
                        let obj = {}
                        for(let i = 0; i < dataheader.length;i++){
                            obj[dataheader[i].field_name_en] = ''
                        }
                        this.formtable[indexstatus-1].tableData.push(obj)
                    }
                }
            }else if(val=='select'){ // 选择
               this.selectName = this.keyName;
            //    let wldadatas = crudModuleListApi(this.keyName);
               this.dialogtitle = '从其他物料档案选择规格'
               this.dialogVisible = true;
               this.selectInfo = this.formtable[0].tableHeader;
            }else if(val=='delete'){ // 删除
                let newdata = [],newselectd=this.formtable[indexstatus-1].deleteData;
                let dataArray = this.formtable[indexstatus-1].tableData;
                let selectids = this.formtable[indexstatus-1].selectData;
                if(selectids.length > 0){
                        for(let i=0; i< dataArray.length;i++){
                            if(!selectids.includes(dataArray[i][this.formtable[indexstatus-1].tableHeader[0].field_name_en])){ // 删除数据
                                newdata.push(dataArray[i]);
                            }else{
                                if(dataArray[i].id){
                                    newselectd.push(dataArray[i].id);
                                }
                            }
                        }
                        this.formtable[indexstatus-1].tableData = newdata;
                        if(newselectd.length > 0){
                            this.formtable[indexstatus-1].deleteData = newselectd;
                        }
                    // this.$modalSure('您确定要删除这条数据,删除后将无法恢复，请确认哦').then(() => {
                    //     for(let i=0; i< dataArray.length;i++){
                    //         if(!selectids.includes(dataArray[i][this.formtable[indexstatus-1].tableHeader[0].field_name_en])){ // 删除数据
                    //             newdata.push(dataArray[i]);
                    //         }else{
                    //             if(dataArray[i].id){
                    //                 newselectd.push(dataArray[i].id);
                    //             }
                    //         }
                    //     }
                    //     if(newselectd.length > 0){
                    //        this.handlerDeleteData(this.formtable[indexstatus-1].value, {ids: newselectd}, newdata, indexstatus);
                    //     }
                    // })
                }else{
                    this.$message.error("请选择要删除的数据")
                }
            }else if(val=='guige'){
                let lbid = 0
                if(this.typeid && this.typeid.includes('-')){
                    lbid = this.typeid.split('-')[0]
                }else{
                    lbid = this.typeid;
                }
                this.getwuliaoleibieList(indexstatus, "leibieguigebiao", {wuliaoleibiebianmaid: lbid})
            }
        },

        // 关联物料档案实体表删除接口
        handlerDeleteData(keyName, data, newdata, indexstatus){
          
                crudModuleBatchDelApi(keyName, data).then((res) => {
                    if(res.status==200){
                        this.formtable[indexstatus-1].tableData = newdata;
                        // this.formtable[indexstatus-1].deleteData = newselectd;
                        if(this.keyName == 'wuliaoqingdanbiao'){
                           EventBus.$emit('event-tree-grandchild', this.formtable[indexstatus-1].tableData)
                        }
                    }
                })
            
           
        },
        
        // 获取物料类别规格列表数据
        async getwuliaoleibieList(indexstatus, keyName, data={}) {
            crudModuleListApi(keyName, data).then((res) => {
                if(res.status==200){
                    let array1 = this.formtable[indexstatus-1].tableData;
                    let array2 = res.data.list;
                    let arr3 = []
                    for(let i=0;i<array2.length;i++){
                        delete array2[i].wuliaoleibiebianmaid;
                        delete array2[i].is_share;
                        delete array2[i].id;
                        array2[i].guigeneirong_two=''
                        if(array2[i].wuliaodanganid){
                            array2[i].wuliaodanganid = ''
                        }else{
                            array2[i].wuliaodanganid = ''
                        }
                        arr3.push(array2[i])
                    }
                    const mergedArray = [...array1, ...arr3];
                    const result = mergedArray.filter(
                    (item, index, self) => index === self.findIndex(t => t.guigedaima === item.guigedaima)
                    );
                    // let tabledata2 = []
                    // result.map((item)=>{
                    //     if(!item.wuliaodanganid){
                    //         item.wuliaodanganid = ''
                    //     }
                    //     tabledata2.push(item)
                    // })
                    this.formtable[indexstatus-1].tableData = result;
                }
            })
        },
       
        // 获取实体表单信息
        getTableFormInput(id, keyName) {
            crudFormInfoApi(id).then((res) => {
                let optiondata = res.data.options;
                if(keyName =='guige'){
                    for(let i=0;i<optiondata.length;i++){
                        if(optiondata[i].name=='状态'){
                            this.optionStatus = optiondata[i].options.optionItems;
                            break;
                        }
                    }
                }
            })
        },
        // 获取规格编码字典数据(添加弹窗显示)
        getGuigezidian(data, indexstatus=0){
            // 调用configDictDataApi函数，传入keyName和0作为参数
            configDictDataApi(data).then((res) => {
                 let resdata = res.data.list;
                 this.diatotal = res.data.count;
                 this.selectInfo = [
                    {
                        field_name: "代码",
                        field_name_en: "value",
                        form_value: "input",
                    },
                    {
                        field_name: "名称",
                        field_name_en: "name",
                        form_value: "input",
                    }
                 ]
                 this.selectData = []
                 let selectedlist = []
                 this.formtable[indexstatus-1].tableData.map((item)=>{
                    selectedlist.push(item.guigedaima)
                 })
                 if(selectedlist.length > 0){
                 for(let i=0;i< resdata.length;i++){
                     if(!selectedlist.includes(resdata[i].value)){
                        this.selectData.push(resdata[i])
                     }
                 }
                }else{
                    this.selectData = resdata
                }
                this.dialogVisible = true;
            })
        },
        // 获取供应商数据(添加弹窗显示)
        async getStTableBase(keyName, formdata, indexstatus=0, fieldData=''){
            crudModuleListApi(keyName, formdata).then((res) => {
                if(res.status==200){
                    let resdata = res.data.list;
                    this.diatotal = res.data.count;
                   
                    let headerData = fieldData.showField;
                    let headerInfo = headerData.slice(0,2)
                    this.selectInfo = headerInfo
                    let fielseniorSearch = fieldData.seniorSearch;
                    let searchForms = {}
                    this.searchField = []
                    for(let i=0;i < fielseniorSearch.length;i++){
                        if(i < 2){
                          searchForms[fielseniorSearch[i].field_name_en] = ''
                          this.searchField.push(fielseniorSearch[i])
                        }
                    }
                    this.searchForm = searchForms
                    this.selectData = []
                    let selectedlist = []
                    this.formtable[indexstatus-1].tableData.map((item)=>{
                        selectedlist.push(item[headerInfo[0].field_name_en])
                    })
                    if(selectedlist.length > 0){
                        if(resdata.length > 0){
                            for(let i=0;i< resdata.length;i++){
                                if(!selectedlist.includes(resdata[i][headerInfo[0].field_name_en])){
                                    this.selectData.push(resdata[i])
                                }
                            }
                        }else{
                            this.selectData = []
                        }
                    }else{
                        this.selectData = resdata
                    }
                    this.dialogVisible = true;     
                }
            })
        },
        
        // 上传文件方法
        uploadServerLog(params) {
            this.percentShow = true
            const file = params.file
            let options = {
            way: 2,
            relation_type: '',
            relation_id: '',
            eid: ''
            }
            uploader(file, 0, options)
            .then((res) => {
                // 获取上传文件渲染页面
                if (res.data.name) {
                   this.imageUrl.push(res.data)
                }
            })
            .catch((err) => {})
        },         
    }
 }

</script>
<style>


</style>